# -*- coding: utf-8 -*-
import time
import os
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr


# 配置示例
CONFIG = {
    # 通知冷却时间(秒)，避免短时间内重复发送相同警报
    'notification_cooldown': 3600,

    # 邮件配置（优先读取环境变量，便于不同环境切换与安全管理）
    'email': {
        'smtp_server': os.getenv('SMTP_SERVER', 'smtp.126.com'),
        'smtp_port': int(os.getenv('SMTP_PORT', '465')),  # 465 常用于 SSL，587 用于 STARTTLS
        'use_tls': os.getenv('SMTP_USE_TLS', 'false').lower() == 'true',  # STARTTLS
        'use_ssl': os.getenv('SMTP_USE_SSL', 'true').lower() == 'true',   # SMTP over SSL
        'sender': os.getenv('SMTP_SENDER', 'wu_319@126.com'),
        'sender_name': os.getenv('SMTP_SENDER_NAME', 'portAI-monitor'),
        'password': os.getenv('SMTP_PASSWORD', 'TUg6wbkD7zpMdZ6a'),
        'receiver': os.getenv('SMTP_RECEIVER', '1421874933@qq.com'),
        'timeout': int(os.getenv('SMTP_TIMEOUT', '10')),
    }
}


def send_email(subject, message, config=CONFIG):
    email_conf = config.get('email', {})
    smtp_server = email_conf.get('smtp_server')
    smtp_port = email_conf.get('smtp_port')
    use_tls = bool(email_conf.get('use_tls'))
    use_ssl = bool(email_conf.get('use_ssl'))
    timeout = email_conf.get('timeout', 10)
    sender = email_conf.get('sender')
    sender_name = email_conf.get('sender_name', sender)
    password = email_conf.get('password')
    receiver = email_conf.get('receiver')

    try:
        msg = MIMEText(message)
        msg['Subject'] = subject
        msg['From'] = formataddr((sender_name, sender))
        msg['To'] = receiver

        # 连接 SMTP 服务器，优先使用 SSL（465），其次 STARTTLS（587），最后明文（25）
        if use_ssl:
            server = smtplib.SMTP_SSL(host=smtp_server, port=smtp_port, timeout=timeout)
        else:
            server = smtplib.SMTP(host=smtp_server, port=smtp_port, timeout=timeout)
        try:
            server.ehlo()
            if not use_ssl and use_tls:
                server.starttls()
                server.ehlo()
            if password:
                server.login(sender, password)
            server.send_message(msg)
        finally:
            try:
                server.quit()
            except Exception:
                pass

        print(f"已发送通知邮件: {subject}")
    except Exception as e:
        # 提供更明确的错误信息，便于排查网络问题/端口阻断/认证失败
        print(f"发送邮件失败: {e} (server={smtp_server}:{smtp_port}, use_ssl={use_ssl}, use_tls={use_tls})")


if __name__ == '__main__':
    current_time = time.time()
    subject = f"警报: Python程序 aaa 已停止运行!"
    message = f"Python程序 aaa 未在运行。请立即检查系统状态。\n*检测时间*: {current_time}"
    send_email(subject, message)
